import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/components/singer_card.dart';
import 'package:flutter_app/components/video_card.dart';
import 'package:flutter_app/model/user_model.dart';
import 'package:flutter_app/model/video_model.dart';
import 'package:flutter_app/services/user_service.dart';
import 'package:flutter_app/services/video_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:video_player/video_player.dart';

class VideoPage extends StatefulWidget {
  VideoPage({Key key}) : super(key: key);

  @override
  VideoPageState createState() => VideoPageState();
}

class VideoPageState extends State<VideoPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller;
  VideoPlayerController _videoController;

  //创建一个多订阅流
  final StreamController<VideoPlayerController> _streamController =
      new StreamController.broadcast();

  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  List<VideoItem> _videoList = VideoList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg = '';

//  String userType = 'DQ_SINGER';
  String userType = '';

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    _scrollController = ScrollController();
    _streamController.stream.listen((event) {
      //当前控制器ID != 传递过来的标识 说明当前传递的是新的标识
      if(_videoController != null && _videoController.textureId != event.textureId){
        _videoController.pause();
      }
      _videoController = event;
    });
    _getSingers();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    _videoController.dispose();
    super.dispose();
  }

  Future _getSingers({bool push = false}) async {
    try {
      //获取数据
//      Map<String, dynamic> result =
//          await VideoService().getVideos(page: page, limit: limit);
      Map<String, dynamic> result;
      String data = await rootBundle.loadString("assets/data/video.json");
      result = jsonDecode(data);
      //将数据转为实体类
      VideoList videoListModel = VideoList.fromJson(result['data']);
      setState(() {
        hasMore = page * limit < result['total'];
        page++;
        if (push) {
          _videoList = videoListModel.list;
        } else {
          _videoList.addAll(videoListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  //上拉加载
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getSingers();
    _controller.resetLoadState();
  }

  //下拉刷新
  Future _onLoad() async {
    if (hasMore) {
      await _getSingers(push: false);
    }
    _controller.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      // 加载时的loading
      // 空视图、异常视图

      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _controller,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //横轴宽度比
            crossAxisSpacing: 1,
            //左右间隔
            mainAxisSpacing: 8,
            crossAxisCount: 2,
            //上下间隔
            childAspectRatio: 9 / 18), //宽高比
        itemCount: _videoList.length,
        itemBuilder: (BuildContext context, int index) {
          bool isEven = index.isEven; //是否是偶数
          double pl = isEven ? 18 : 9;
          double pr = isEven ? 9 : 18;
          return Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: 16, left: pl, right: pr),
              child: VideoCard(
                videoItem: _videoList[index],
                streamController: _streamController,
              ));
        },
        padding: EdgeInsets.only(top: 8),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
